/*
 * @Author: your name
 * @Date: 2021-06-20 22:27:16
 * @LastEditTime: 2021-09-07 22:05:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hbs\libs\redis\redis.ts
 */
const redis = require("redis");
export default class Rds {
    public cli;
    constructor(host: string = "localhost", port: number = 6379, password: string = "") {
        this.cli = redis.createClient(port, host);
        if (password != "") {
            this.cli.auth(password);
        };
        this.cli.on('connect', () => {
            //链接成功后可以执行的代码
        });
    }
    private static _INPUT(value): any {
        typeof (value) === "object" ? value = JSON.stringify(value) : value;
        return value;
    }
    private static _OUTPUT(v): any {
        try{
            typeof (v) === "string" ? v = JSON.parse(v) : v;
            return v;
        }catch{
            return v;
        }
     
    }
    public flushall(): void {
        this.cli.flushall();
    }
    public get(key): Promise<any> {
        return new Promise((resolve, reject) => {
            this.cli.get(key, (err, v) => {
                resolve(Rds._OUTPUT(v));
                reject(err);
            });
        });

    }
    public set(key, value): Promise<any> {
        value = Rds._INPUT(value);
        return new Promise((resolve, reject) => {
            this.cli.set(key, value, (err, v) => {
                resolve(v);
                reject(err);
            });
        });
    }
    public expire(key, seconds: number): Promise<any> {
        return new Promise((resolve, reject) => {
            this.cli.expire(key, seconds, (err, v) => {
                resolve(v);
                reject(err);
            });
        });



    }
    public hget(key, field): Promise<any> {
        return new Promise((resolve, reject) => {
            this.cli.hget(key, field, (err, v) => {
                resolve(Rds._OUTPUT(v));
                reject(err);
            });
        });
    }
    public hset(key, field, value): Promise<any> {
        value = Rds._INPUT(value);
        return new Promise((resolve, reject) => {
            this.cli.hset(key, field, value, (err, v) => {
                resolve(v);
                reject(err);
            });
        });

    }
}